package com.eportal.action.background;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TAgent;
import com.eportal.domain.TCommunity;
import com.eportal.service.SysOptService;
import com.eportal.service.TAgentService;
import com.eportal.service.TCommunityService;
import com.eportal.util.MD5;
import com.eportal.util.ValidateUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;

/**
 * SysOptAction
 *
 * @author chencheng
 * @date 2016/05/16
 */
public class SysOptAction extends BaseAction implements ModelDriven<Sysopt> {

    private Logger log = Logger.getLogger(SysOptAction.class.getName());

    Map<String, Object> result = new HashMap<String, Object>();
    @Autowired
    private SysOptService sysOptService;
    @Autowired
    private TCommunityService tCommunityService;
	/**
     * 用户管理页面
     */
    public String listView() {
        return "listView";
    }
    
    /**
     * 用户列表
     */
    public void page() throws Exception {
        JqGridPager page = new JqGridPager();
        setPage(getRequest(), page);
        Sysopt  user= (Sysopt)getSession().getAttribute("user");
        int userRole =  (Integer) getSession().getAttribute("userRole");
        String sql  = sqlWhere(user,userRole);
        List<Map<String, Object>> users = sysOptService.list(page,sql);
        jqGridQueryMap(Sysopt.class, getRequest(), users, getResponse(), page);
    }
    
    /**
     * 用户list用于选择
     */
    public void list() throws Exception {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String type = getRequest().getParameter("type");
    	StringBuilder where = new StringBuilder("from Sysopt where 1=1 ");
    	//内部账号
    	if (StringUtils.isBlank(type)) {
    		where.append("and agtCode ='");
    		where.append(user.getAgtCode());
    		where.append("' ");
    		where.append("and communityId ='");
    		where.append(user.getCommunityId());
    		where.append("' ");
		}else if("allComu".equals(type)){
			where.append(" and rLevel ='2'");
		}else if("area".equals(type)){
			where.append(" and rLevel ='5'");
		}
    	
    	List<Sysopt> Sysopts = sysOptService.list(where.toString());
        responseBody(Sysopts);
    }
    
    /**
     * 查询条件组合
     */
    private String sqlWhere(Sysopt user, int userRole) {
    	StringBuilder where = new StringBuilder("select * from Sysopt where 1=1 ");
    	if(userRole != 1){
    		if(userRole == 2){//非平台超级管理员
    			where.append("and isAdmin !='-1'");
    		}else if(userRole == 3 || userRole == 4){//合作方管理员，管理合作方内部，及下级社区
    			where.append("and agtCode ='");
    			where.append(user.getAgtCode());
    			where.append("' ");
    			where.append("and isAdmin !='1'");
    		}else { //社区管理员，只管理社区
    			where.append("and agtCode ='");
    			where.append(user.getAgtCode());
    			where.append("' ");
    			where.append("and communityId ='");
    			where.append(user.getCommunityId());
    			where.append("' ");
    			where.append("and isAdmin !='1'");
    		}
    		where.append(" and sid !=");
    		where.append(user.getSid());
    	}
    	String username = getRequest().getParameter("username");
    	if (StringUtils.isNotBlank(username)) {
    		where.append(" and username like'%"+username+"%'");
    	}
    	String uname = getRequest().getParameter("uname");
    	if (StringUtils.isNotBlank(uname)) {
    		where.append(" and uname like'%"+uname+"%'");
    	}
    	
    	StringBuilder sb = new StringBuilder("select Syso.* from (");
    	if (userRole == 3 || userRole == 4) {
    		where.append(" union all select * from Sysopt where ");
        	where.append("agtCode ='");
        	where.append(user.getAgtCode());
        	where.append("' ");
        	where.append("and isAdmin = '1' and rLevel='2' ");
		}
    	

    	
        sb.append(where);
    	sb.append(") Syso");
		return sb.toString();
	}
	/**
     * 用户新增
     */
    public String addView() {
        return "addView";
    }
    
    /**
     * 用户保存
     */
    public void add(){
    	Sysopt sysopt = getModel();
    	result = sysOptService.addMethod(sysopt);
        responseBody(result);
    }
    
    
    
    
    /**
     * 超级社区管理员创建保存
     */
    public void creatTcoManager() throws IOException {
        String msg = ValidateUtil.validate(getModel());
        if (msg == null || msg.trim().length() == 0) {
            try {
            	Sysopt  user= (Sysopt)getSession().getAttribute("user");
            	if(sysOptService.ifUserExist(sysopt)){
            		result.put("code", 0);
                    result.put("msg", "用户名已存在");
                    responseBody(result);
                    return;
            	}
            	if(sysOptService.ifUserRoleExist(sysopt.getRoles())){
            		result.put("code", 0);
                    result.put("msg", "该超级管理员角色下用户已存在");
                    TCommunity tCommunity = tCommunityService.get(Long.parseLong(sysopt.getCommunityId()));
//                	tCommunity.setcManager(1);
                	tCommunityService.update(tCommunity);
                    responseBody(result);
                    return;
            	}
            	sysopt.setIsAdmin("1");
            	sysopt.setrLevel(2);
            	sysopt.setcName(Long.toString(user.getSid()));
            	sysopt.setcTime(new Timestamp(System.currentTimeMillis()));
            	sysopt.setPasswd(MD5.MD5Encode(sysopt.getPasswd()));
            	sysOptService.save(sysopt);
            	
            	TCommunity tCommunity = tCommunityService.get(Long.parseLong(sysopt.getCommunityId()));
            	if (tCommunity != null) {
//            		tCommunity.setcManager(1);
            		tCommunityService.update(tCommunity);
            		 result.put("code", 1);
            		 result.put("msg", "操作成功");
				}else{
					result.put("code", 1);
					result.put("msg", "公司状态更新失败，不影响使用");
				}
            } catch (Exception e) {
                log.error("添加合作方超级管理员失败", e);
                result.put("code", 0);
                result.put("msg", "操作失败");
            }
        } else {
            result.put("msg", msg);
        }
        responseBody(result);
    }
    
    
    /**
     * 判断是否有对操作员的修改权限，用于页面判断
     * @throws IOException 
     */
    public void ifHasRole1() throws IOException {
    	Sysopt sysopt1 = sysOptService.get(sysopt.getSid());
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if(userRole == 1){//平台超级管理员
    		result.put("code", 0);
            result.put("msg", "有修改权限");
            responseBody(result);
            return;
    	}
    	//是否属于内部人员
    	if(sysopt1.getAgtCode().equals(user.getAgtCode()) && sysopt1.getCommunityId().equals(user.getCommunityId())){
    		result.put("code", 0);
            result.put("msg", "有修改权限");
            responseBody(result);
            return;
    	}
		if(userRole == 2){
    		//平台普通管理员可以修改合作方超级管理员的密码
    		if("1".equals(sysopt1.getIsAdmin()) && sysopt1.getrLevel()==1){
    			result.put("code", 1);
                result.put("msg", "可以修改合作方超级管理员密码");
                responseBody(result);
    			return;
    		}
    	}
    	if(userRole == 3 || userRole == 4){
    		if("1".equals(sysopt1.getIsAdmin()) && sysopt1.getrLevel()==2){//判断是否是社区超级管理员
    			result.put("code", 1);
                result.put("msg", "可以修改社区超级管理员密码");
                responseBody(result);
    			return;
    		}
    	}
		result.put("code", 2);
        result.put("msg", "没有修改权限");
        responseBody(result);
	}
    
   
	
    /**
     * 用户更新页面
     */
    public String updateView() {
        Sysopt sysopt = sysOptService.get(getModel().getSid());
        getRequest().setAttribute("user", sysopt);
        if(("1".equals(sysopt.getIsAdmin()) && sysopt.getrLevel()==1) || ("1".equals(sysopt.getIsAdmin()) && sysopt.getrLevel()==2)){
        	return "updateManagreView";
        }
//        int userRole =  (Integer) getSession().getAttribute("userRole");
//        if (userRole == 1) {
//        	if(("0".equals(sysopt.getIsAdmin()) && sysopt.getrLevel()==1) || ("0".equals(sysopt.getIsAdmin()) && sysopt.getrLevel()==2)){
//        		return "updateManagreView";
//			}
//		}
        return "updateView";
    }

    /**
     * 超级管理员用户更新密码保存
     */
    public void updateManager(){
    	Sysopt sysopt = getModel();
    	result = sysOptService.updateManagerMethod(sysopt);
        responseBody(result);
    }
    
    /**
     * 用户更新保存
     */
    public void update(){
    	Sysopt sysopt = getModel();
    	result = sysOptService.updateMethod(sysopt);
        responseBody(result);
    }

    /**
     * 用户删除
     */
    public void delete(){
    	String ids = getRequest().getParameter("ids");
    	result = sysOptService.deleteMethod(ids);
        responseBody(result);
    }
    
    /**
     * 用户修改密码
     */
    public String changePassword() {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
         getRequest().setAttribute("user", user);
        return SUCCESS;
    }
    
    /**
     * 用户修改密码
     */
    public void updatePassword(){
    	String sid = getRequest().getParameter("sid");
    	String oldPassword = getRequest().getParameter("oldPassword");
    	String newPassword = getRequest().getParameter("newPassword");
    	result = sysOptService.updatePasswordMethod(sid,oldPassword,newPassword);
        responseBody(result);
    }
    
    @Override
    public Sysopt getModel() {
        return sysopt;
    }

    private Sysopt sysopt = new Sysopt();
}
